from django.shortcuts import render

from rest_framework.views import APIView
from rest_framework.response import Response
# 导入原生sql模块
from django.db import connection
from django.http import HttpResponse
import json
from practical_training.models import TypeDemo, Cate, WorkOrder, Message
from practical_training.serializers import CateSer, WorkOrderSer, MessageSer
from myapp.models import User
from myapp.serializers import UserSer

from pymongo import MongoClient

from bson import json_util as jsonb

# 导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

# import pymongoclient = pymongo.MongoClient(host='localhost', port=27017)	# 也可以起到连接mongo的效果


# websocket接口
# 客户端列表
clients = {}

@accept_websocket
def websocketlink(request):
    if request.is_websocket():

        userid = str(uuid.uuid1())

        while True:

            message = request.websocket.wait()

            if not message:
                break
            else:
                print('websocket链接成功' + str(message))
                clients[userid] = request.websocket


# 推送消息
def sendmessage(request):
    # 获取消息
    msg = request.GET.get("msg")

    for client in clients:
        clients[client].send(msg.encode('utf-8'))

    return HttpResponse({'message': "ok"})



# 消息撤回
# class Withdraw(APIView):

# 	def get(self, request):

# 		# 连接mongo
# 		client = MongoClient('mongodb://localhost:27017')

# 		# 指定表
# 		db = client.work

# 		# 指定集合
# 		collection = db.studentscollection = db['eventlog']

# 		# 创建索引
# 		collection.createIndex({"lastModifiedDate":1},{expireAfterSeconds:60})	# expireAfterSeconds:超过60秒自动删除索引

# 		# 添加数据
# 		collection.insert({"title":"mongodb 1","lastModifiedDate":new Date()})
# 		collection.insert({"title":"mongodb 2","lastModifiedDate":new Date()})
# 		collection.insert({"title":"mongodb 3","lastModifiedDate":new Date()})
# 		collection.insert({"title":"mongodb 4","lastModifiedDate":new Date()})






# 排序展示  未读的最新数据在最前
class MessageOrder(APIView):

	def get(self, request):

		message = Message.objects.all().order_by('is_read','-id')

		message_ser = MessageSer(message, many=True)

		return Response({'message': 'ok','data': message_ser.data})



# 消息提醒类
class MessageView(APIView):

	def get(self, request):

		count = Message.objects.filter(is_read=0).count()

		return Response({'count':count})

	def put(self, request):

		Message.objects.all().update(is_read=1)

		return Response({'message': '已阅'})



# 获取工单信息审批状态
class GetWorkStatus(APIView):

	def get(self, request):

		wid = request.GET.get('wid')

		work = WorkOrder.objects.filter(id=wid).first()

		work_status = work.status

		return Response({'status': work_status})


# 并审
class Approver(APIView):

	def get(self, request):

		aid = request.GET.get('aid')

		wid = request.GET.get('wid')

		work_obj = WorkOrder.objects.filter(id=wid).first()

		work_info = eval(work_obj.alist)

		if aid in work_info[0]:

			return Response({'message': '审批成功', 'code': 200})
		else:
			return Response({'message': '拒绝审批', 'code': 400})



# 接收审批结果参数存入数据库,读取审批结果信息
class WorkAlist(APIView):

	def post(self, request):

		aid = request.POST.get('aid')

		wid = request.POST.get('wid')

		if int(aid) == 4 or 10:

			work = WorkOrder.objects.filter(id=wid).first()

			work_ser = WorkOrderSer(instance=work,data={'alist':aid},partial=True)

			if work_ser.is_valid():

				work_ser.save()

			work_obj = WorkOrder.objects.filter(id=wid).first()

			if work_obj.alist == 10:

				work_ser1 = WorkOrderSer(instance=work_obj,data={'status':1},partial=True)

				if work_ser1.is_valid():

					work_ser1.save()

				return Response({'message': '审批通过', 'code': 200})
			else:

				work_ser2 = WorkOrderSer(instance=work_obj,data={'status':3},partial=True)

				if work_ser2.is_valid():

					work_ser2.save()

				return Response({'message': '审批通过', 'code': 200})
		else:

			return Response({'message': '您没有审批权限', 'code': 400})


class Refuse(APIView):

	def post(self, request):

		aid = request.POST.get('aid')

		wid = request.POST.get('wid')

		if int(aid) == 4 or 10:

			work = WorkOrder.objects.filter(id=wid).first()

			work_ser = WorkOrderSer(instance=work,data={'status':0},partial=True)

			if work_ser.is_valid():

				work_ser.save()

			return Response({'message': '审批已拒绝', 'code': 200})



# 查看工单表信息
class WorkOrderInfo(APIView):

	def get(self, request):

		workorder = WorkOrder.objects.all()

		formdata_dict = []

		for i in workorder:

			formdata_dict.append(eval(i.formdata))

		return Response(formdata_dict)




# 查看该登录用户提交的工单详情  mysql
class GetWorkDetail(APIView):

	def get(self, request):

		uid = request.GET.get('uid')

		workorder = WorkOrder.objects.filter(uid=uid)

		formdata_dict = []

		for i in workorder:

			formdata_dict.append(eval(i.formdata))

		return HttpResponse(jsonb.dumps(formdata_dict, ensure_ascii=False))



# 添加工单表信息
class WorkForm(APIView):

	def post(self, request):

		data = request.data
		tid = data.get('pid')

		if int(tid) == 3:
			uid = data.get('uid')
			a = data.get('approver[0]')
			b = data.get('approver[1]')
			aid = []
			aid.append(a)
			aid.append(b)
			a_list = str(aid)

			formdata = {}.fromkeys(['staff','cause','price'])
			formdata["staff"] = data.get('staff')
			formdata["cause"] = data.get('cause')
			formdata["price"] = data.get('price')

			work = WorkOrder(uid=uid, alist=a_list, formdata=formdata, tid=tid, status=0)
			work.save()

			w = WorkOrder.objects.all()

			alist = []

			for i in w:
				alist.append(i.id)

			for i in range(len(alist)-1):
				for j in range(len(alist)-i-1):
					if alist[j] < alist[j+1]:
						alist[j],alist[j+1] = alist[j+1],alist[j]

			mess = Message(uid=uid, wid=alist[0], tid=tid, is_read=0)

			mess.save()

			return Response({'message':'提交成功', 'code':200})
		if int(tid) == 2:
			uid = data.get('uid')
			a = data.get('approver[0]')
			b = data.get('approver[1]')
			aid = []
			aid.append(a)
			aid.append(b)
			a_list = str(aid)

			formdata = {}.fromkeys(['staff','cause','start_time','end_time'])
			formdata["staff"] = data.get('staff')
			formdata["cause"] = data.get('cause')
			formdata["start_time"] = data.get('start_time')
			formdata["end_time"] = data.get('end_time')

			work = WorkOrder(uid=uid, alist=a_list, formdata=formdata, tid=tid, status=0)
			work.save()

			w = WorkOrder.objects.all()

			alist = []

			for i in w:
				alist.append(i.id)

			for i in range(len(alist)-1):
				for j in range(len(alist)-i-1):
					if alist[j] < alist[j+1]:
						alist[j],alist[j+1] = alist[j+1],alist[j]

			mess = Message(uid=uid, wid=alist[0], tid=tid, is_read=0)

			mess.save()
			
			return Response({'message':'提交成功', 'code':200})
		else:
			return Response({'message':'提交失败', 'code':400})



# 获取审批人
class GetApprover(APIView):

	def get(self, request):

		pid = request.GET.get('pid')

		cate = Cate.objects.filter(id=pid).first()

		cate_str = cate.approver

		cate_list = eval(cate_str)

		user = []
		user_obj = User.objects.all()
		for i in cate_list:
			# userobj = user_obj.filter(id=i).first()
			# user.append(userobj.username)

			user.append(user_obj.filter(id=i).first())
		
		user_data = UserSer(user, many=True)

		return Response(user_data.data)



# 获取工单分类，添加分类信息
class GetDataInfo(APIView):

	def get(self, request):

		pid = request.GET.get('pid')

		typedemo = TypeDemo.objects.filter(pid=pid).first()

		if typedemo:

			fields_obj = eval(typedemo.admin_fields)

			return Response(fields_obj)
		else:

			return Response({'message': '没有此分类'})

	def post(self, request):

		data1 = request.data

		data = dict(data1)

		pid = request.POST.get('pid')
		
		client = MongoClient('mongodb://localhost:27017/')	# 连接mongo数据库

		db = client.course	# 指定表

		collection = db.studentscollection = db['formdata']		# 指定集合

		formdata = data

		result = collection.insert(formdata)	# 添加数据

		print(result)

		return Response({'message': '提交成功', 'code': 200})


# 查看工单分类
class GetCate(APIView):

	def get(self, request):

		cate_obj = Cate.objects.filter(pid=0)
		cate_ser = CateSer(cate_obj, many=True)
		return Response(cate_ser.data)


# 查看工单详情  mongo
class GetCateDetail(APIView):

	def get(self, request):

		pid = request.GET.get('pid')

		client = MongoClient("mongodb://localhost:27017")

		db = client.course

		find = db.formdata.find({'pid':pid})

		return HttpResponse(jsonb.dumps(find, ensure_ascii=False))



# ----------------------------------------------------------------

# 列表推导式强转
def dictfetchall(cursor):

    desc = cursor.description

    return [

    dict(zip([col[0] for col in desc],row))

    for row in cursor.fetchall()

    ]


# 构造课程关系层级关系(树形结构)
def get_tree(data):

	lists = []
	tree = {}

	for item in data:
		tree[item['id']] = item

	for i in data:
		if not i['pid']:
			lists.append(tree[i['id']])
		else:
			parent_id = i['pid']
			if "children" not in tree[parent_id]:
				tree[parent_id]["children"] = []
			tree[parent_id]["children"].append(tree[i['id']])

	return lists


# 获取课程分类
def get_cate(request):
    # 建立查询游标
    cursor = connection.cursor()
    # 指行sql语句
    cursor.execute('SELECT * from cate')
    # 获取结果集
    res = dictfetchall(cursor)
    # 强转
    res = get_tree(res)
    return HttpResponse(json.dumps(res, indent=4, ensure_ascii=False), content_type='application/json')


class Test1(APIView):

	def get(self, request):
		data = request.GET.get('data')
		print(data)

		return Response({'code': 200})











